/**
 * Deal with feed .
 * @author William
 * 2012-1-14
 */

package com.ytu.irss;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class IRSSHandler extends DefaultHandler {

	RSSFeed RSSFeed;
	RSSItem RSSItem;

	String lastElementName = "";

	private int currentState = 0;

	final int RSS_TITLE = 1;
	final int RSS_LINK = 2;
	final int RSS_DESCRIPTION = 3;
	final int RSS_CATEGORY = 4;
	final int RSS_PUBDATE = 5;

	public IRSSHandler() {

	}

	public RSSFeed getFeed() {
		return RSSFeed;
	}

	public void startDocument() throws SAXException {
		RSSFeed = new RSSFeed();
		RSSItem = new RSSItem();
	}

	public void endDocument() throws SAXException {

	}

	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {

		if (localName.equals("item")) {
			RSSItem = new RSSItem();
			return;
		} else if (localName.equals("channel")) {
			currentState = 0;
			return;
		} else if (localName.equals("title")) {
			currentState = RSS_TITLE;
			return;                  
		} else if (localName.equals("description")) {
			currentState = RSS_DESCRIPTION;
			return;
		} else if (localName.equals("link")) {
			currentState = RSS_LINK;
			return;
		} else if (localName.equals("category")) {
			currentState = RSS_CATEGORY;
			return;
		} else if (localName.equals("pubDate")) {
			currentState = RSS_PUBDATE;
			return;
		}
		currentState = 0;

	}

	public void characters(char ch[], int start, int length) {
		String str = new String(ch, start, length);
		switch (currentState) {
		case RSS_TITLE:
			RSSItem.setTitle(str);
			currentState = 0;
			break;
		case RSS_LINK:
			RSSItem.setLink(str);
			currentState = 0;
			break;
		case RSS_DESCRIPTION:
			RSSItem.setDescription(str);
			currentState = 0;
			break;
		case RSS_CATEGORY:
			RSSItem.setCategory(str);
			currentState = 0;
			break;
		case RSS_PUBDATE:
			RSSItem.setPubDate(str);
			currentState = 0;
			break;
		default:
			return;

		}
	}

	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		if (localName.equals("item")) {
			RSSFeed.addItem(RSSItem);
			return;
		}

	}

}
